package com.crazymakercircle.objectpool;

import com.crazymakercircle.util.Print;
import org.apache.commons.pool2.KeyedPooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericKeyedObjectPool;

public class MyPooledObjectFactory implements KeyedPooledObjectFactory<CacheKey, CacheObject> {
    @Override
    public void activateObject(CacheKey s, PooledObject<CacheObject> pooledObject) throws Exception {
        Print.tcfo("Factory callback ..  激活对象， 借用时调用 this method ");
    }

    @Override
    public void destroyObject(CacheKey s, PooledObject<CacheObject> pooledObject) throws Exception {
        Print.tcfo("Factory callback .. 销毁对象");
    }

    @Override
    public PooledObject<CacheObject> makeObject(CacheKey s) throws Exception {
        Print.tcfo("Factory callback .. 创建对象");
        CacheObject object = new CacheObject(s.key);
        return new DefaultPooledObject(object);
    }


    @Override
    public void passivateObject(CacheKey s, PooledObject<CacheObject> pooledObject) throws Exception {
        Print.tcfo("Factory callback .. 钝化对象，归还时调用 this method ");
    }

    @Override
    public boolean validateObject(CacheKey s, PooledObject<CacheObject> pooledObject) {
        Print.tcfo("Factory callback .. 判断对象是否可用");
        return pooledObject.getObject().valid();
    }



}
